package edu.imac.angryfood.component;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;

import org.jbox2d.common.Vec2;
import org.newdawn.slick.SlickException;

import edu.imac.angryfood.world.World;

/** A projectile that makes a U-turn when the user clicks and it is still in the air */

public class BoomerangProjectile extends AbstractProjectile {	
	
	/** the velocity of the boomerang when it is clicked */
	private float velocityX;
	/** timer that U-turns the boomerang */
	private Timer t;
	/** number of iteration of t for the U-turn */
	private int count;
	
	/** constructor for circle projectiles
	 * 
	 * @param x x position of the projectile
	 * @param y y position of the projectile
	 * @param radius radius of the projectile
	 * @param droped if the projectile has already been droped
	 * @param num the order in which the projectile will be launched
	 * @param image the name of the image's file
	 */
	
	public BoomerangProjectile(int x, int y, float radius, boolean droped, int num, String image)
			throws SlickException {
		super(x, y, radius, droped, num, image);
	}
	
	/** constructor for rectangle projectiles
	 * 
	 * @param x x position of the projectile
	 * @param y y position of the projectile
	 * @param width width of the projectile
	 * @param height height of the projectile
	 * @param droped if the projectile has already been droped
	 * @param num the order in which the projectile will be launched
	 * @param image the name of the image's file
	 */
	
	public BoomerangProjectile(int x, int y, int width, int height, boolean droped, int num, String image)
			throws SlickException {
		super(x, y, width, height, droped, num, image);
	}

	/** when the user clicks, the boomerang makes a U-turn 
	 * 
	 * @param world the world that contains the game
	 * @throws SlickException
	 */
	
	@Override
	public void click(World world) throws SlickException {
		if (tLaunched instanceof Timer){
			tLaunched.stop();
		}
		clicked=true;
		next(world);
		Vec2 velocity=getLinearVelocity();
		velocityX=velocity.x;
		count=0;
		// the x velocity is inversed in 0.5 seconds 
		t = new Timer (50, new ActionListener(){
			public void actionPerformed(ActionEvent e){
				Vec2 velocity=getLinearVelocity();
				velocity.x-=velocityX/5;
				count++;
				getJBoxBody().setLinearVelocity(velocity);
				if (count>10 || velocity.x<-velocityX){
					t.stop();
				}
			}

		});
		t.start();	
		
	}

	/** when the projectile collides something, it cannot be clicked anymore
	 * 
	 * @param world the world that contains the game
	 */
	@Override
	public void collision(World world) {
		
		if (!collided){
			if (tLaunched instanceof Timer){
				tLaunched.stop();
			}
			collided=true;
			clicked=true;
			if (t instanceof Timer){
				t.stop();
			}
			next(world);	
		}
	}

}
